<?php
namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Overtrue\EasySms\EasySms;
use Illuminate\Support\Facades\Config;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;

class UserController extends Controller
{
    private $salt;
    public function __construct()
    {
        $this->salt = "userloginregister";
    }
//        初始化
    public function initialize(Request $request){
        $data = $request->all();
        if(empty($data)){
            return  response()->json(['code'=>400,'msg'=>'初始化失败','data'=>'']);
        }
        $device = DB::table('device')->where('idfa','=',$data['idfa'])->first();
        if(empty($device)){
            $res = DB::table('device')->insert(
                [
                    'idfa' => $data['idfa'],
                    'uuid' => $data['uuid'],
                    'model' => $data['model'],
                    'devToken' => $data['devToken'],
                    'width' => $data['width'],
                    'height' => $data['height'],
                    'countryCode' => $data['countryCode'],
                    'language' => $data['language'],
                    'osName' => $data['osName'],
                    'osVersion' => $data['osVersion'],
                    'appId' => $data['appId'],
                    'channelId' => $data['channelId'],
                    'subChannelId' => $data['subChannelId'],
                    'version' => $data['version'],
                    'versionCode' => $data['versionCode'],
                    'createdAt' => time(),
                    'updatedAt' =>  time(),
                    'packageName' => $data['packageName']
                ]);
        }else{
            $res = 1;
        }
        if(!$res){
            return response()->json(['code'=>400,'msg'=>'初始化失败','data'=>'']);
        }else{
            return  response()->json(['code'=>200,'msg'=>'初始化成功','data'=>'']);
        }
    }
//     发送短信
    public function allSendMessage(Request $request){
        $data = $request->all();
        $mobile =$data['mobile'] ?? "";
        $type = $data['type'] ?? " ";
        if(empty($data)){
            return  response()->json(['code'=>400,'msg'=>'请输入手机号','data'=>'']);
        }
        $use=User::where('mobile',$mobile)->first();
        if($type=="1"){
            if(!empty($use)){
                return  response()->json(['code'=>400,'msg'=>'手机号已被注册','data'=>'']);
            }
        }
        if($type=="2"){
            if(empty($use)){
                return  response()->json(['code'=>400,'msg'=>'手机号未注册','data'=>'']);
            }
        }
        if(empty($mobile) || strlen($mobile)!=11){
            return  response()->json(['code'=>400,'msg'=>'手机号错误','data'=>'']);
        }
        $mobileExpire = Redis::exists($mobile);
        if($mobileExpire){
            return  response()->json(['code'=>400,'msg'=>'验证码已发送','data'=>'']);
        }
        $config = Config::get('info.message_config');
        $easySms = new EasySms($config);
        $code = rand(1000,9999);
        $redMobile = Redis::exists($mobile.'code');
        if($redMobile){
            $redCode = Redis::get($mobile.'code');
            Redis::del($mobile.'code');
        }
        $redTime = Redis::exists($mobile.'time');
        if($redTime){
            $redTime = Redis::get($mobile.'time');
            Redis::del($mobile.'time');
        }
        try{
            $result=$easySms->send($mobile, [
                'content' => '您的验证码${code}，该验证码5分钟内有效，请勿泄漏于他人！',
                'template' => 'SMS_126570108',
                'data' => [
                    'code' => $code,
                ],
            ]);
        }catch(NoGatewayAvailableException $e){
            
            return  response()->json(['code'=>200,'msg'=>'由于您操作次数过多，5分钟后再进行操作','data'=>'']);
        }
        Redis::setex($mobile.'code', 300, $code);
        Redis::setex($mobile.'time', 300, time());
        Redis::setex($mobile,60, $mobile);
        if($result['aliyun']['status']=='success'){
            return  response()->json(['code'=>200,'msg'=>'短信发送成功','data'=>'']);
        }else{
            return  response()->json(['code'=>200,'msg'=>'短信发送成功','data'=>'']);
        }
    }
//      验证码验证
    public function verifyMessage(Request $request){
        $data = $request->all();
        if(empty($data)){
            return  response()->json(['code'=>400,'msg'=>'验证失败','data'=>'']);
        }
        $mobile = $data['mobile'];
        $posytMessage = $data['code'];
        $nowTime = time();
        $redisMessage  = Redis::get($mobile.'code');
        $redisTime = Redis::get($mobile.'time');
        $timeApart = $nowTime - $redisTime;
        if($timeApart < 0 || $timeApart > 300 || ($redisMessage != $posytMessage))
        {
            return response()->json(['code'=>400,'msg'=>'验证码错误或失效','data'=>'']);
        }
        $info = str_random(20);
        Redis::setex($mobile.'info', 300, $info);
        Redis::setex($mobile.'infoTime', 300, time());
        return response()->json(['code'=>200,'msg'=>'验证成功','data'=>['info'=>$info]]);
    }
//    注册表单提交
    public function register(Request $request){
        $data = $request->all();
        $salt = str_random(6);
        $pwd = md5($data['pwd'].$salt);
        $mobile = $data['mobile'];
        $type = $data['type'];
        if(empty($mobile) || empty($pwd) || empty($type))
        {
            return response()->json(['code'=>400,'msg'=>'信息错误','data'=>['token'=>'']]);
        }
        $use=User::where('mobile',$mobile)->first();
        if($use)
        {
            return response()->json(['code'=>400,'msg'=>'手机号已注册','data'=>['token'=>'']]);
        }
        if($type=="1"){
            $postMessage = $data['info'];
            $redisMessage  = Redis::get($mobile.'info');
            $redisTime = Redis::get($mobile.'infoTime');
            $ipadToken = md5(str_random(30).time());
            $ipadValidity = time()+7*24*3600;
            $token = md5(str_random(30).time());
            $validity = time()+7*24*3600;
            $idfa = $data['idfa'];
        }
        if($type=="2"){
            $postMessage = $data['message'];
            $redisMessage  = Redis::get($mobile.'code');
            $redisTime = Redis::get($mobile.'time');
            $token = md5(str_random(30).time());
            $validity = time()+7*24*3600;
            $ipadToken = md5(str_random(30).time());
            $ipadValidity = time()+7*24*3600;
            $idfa ='';
        }
        $nowTime = time();
        $newTime = $nowTime + 10;
        $timeApart = $nowTime - $redisTime;
//        if($timeApart<0 || $timeApart>300){
//            return response()->json(['code'=>400,'msg'=>'验证码已过期','data'=>['token'=>'']]);
//        }
        if( $postMessage != $redisMessage)
        {
            return response()->json(['code'=>400,'msg'=>'验证码错误','data'=>['token'=>'']]);
        }
        $userId = DB::table('userAdm')->insertGetId(
            ['mobile' => $mobile, 'passWord' => $pwd, 'salt'=>$salt,'apiToken' => $token,'createdAt'=>$nowTime,'validity'=>$validity,'updatedAt'=>$newTime,'ipadToken' => $ipadToken,'ipadValidity'=>$ipadValidity]
        );
        if(empty($userId))
        {
            return response()->json(['code'=>400,'msg'=>'注册失败','data'=>['token'=>'']]);
        }
        if($type == '1'){
            $loginId =  DB::table('multiDeviceLogin')->insertGetId(
                ['uid'=>$userId,'mobile' => $mobile,'type'=>1, 'idfa'=>$idfa,'token' => $ipadToken,'createdAt'=>$nowTime,'validity'=>$validity]
            );
        }
        try {
            $cmpId = DB::table('cmpInfo')->insertGetId(
                ['userId' => $userId, 'cmpName' => '','cmpWelcome'=>'','cmpLogo'=>'company/logo.png','cmpBgImg'=>'company/back.png','isMessageOn'=>0,'status'=>0,'isMailOn'=>0]
            );
            $visId = DB::table('visitorType')->insertGetId(
                ['cmpId' => $cmpId, 'typeName' => '面试','status'=>1,'isAdd'=>0,'type'=>1]
            );
            $busId = DB::table('visitorType')->insertGetId(
                ['cmpId' => $cmpId, 'typeName' => '商务','status'=>1,'isAdd'=>0,'type'=>2]
            );
            $perId = DB::table('visitorType')->insertGetId(
                ['cmpId' => $cmpId, 'typeName' => '亲友','status'=>1,'isAdd'=>0,'type'=>3]
            );
            $othId = DB::table('visitorType')->insertGetId(
                ['cmpId' => $cmpId, 'typeName' => '其他','status'=>1,'isAdd'=>0,'type'=>4]
            );
//            面试
            DB::table('visitorTypeSet')->insert([
                ['cmpId' => $cmpId, 'visitorTypeId' => $visId,'typeName' => '拍照','isHidden'=>1,'type'=>0,'isRequired'=>0,'typeSign'=>1],
                ['cmpId' => $cmpId, 'visitorTypeId' => $visId,'typeName' => '性别','isHidden'=>0,'type'=>1,'isRequired'=>0,'typeSign'=>2],
                ['cmpId' => $cmpId, 'visitorTypeId' => $visId,'typeName' => '邮箱','isHidden'=>1,'type'=>0,'isRequired'=>0,'typeSign'=>4],
                ['cmpId' => $cmpId, 'visitorTypeId' => $visId,'typeName' => '身份证','isHidden'=>0,'type'=>0,'isRequired'=>0,'typeSign'=>6],
                ['cmpId' => $cmpId, 'visitorTypeId' => $visId,'typeName' => '备注','isHidden'=>1,'type'=>0,'isRequired'=>0,'typeSign'=>7]
            ]);
//            亲友
            DB::table('visitorTypeSet')->insert([
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $perId,'typeName' => '拍照','isHidden'=>1,'type'=>0,'isRequired'=>0,'typeSign'=>1],
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $perId,'typeName' => '性别','isHidden'=>0,'type'=>1,'isRequired'=>0,'typeSign'=>2],
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $perId,'typeName' => '邮箱','isHidden'=>1,'type'=>0,'isRequired'=>0,'typeSign'=>4],
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $perId,'typeName' => '身份证','isHidden'=>0,'type'=>0,'isRequired'=>0,'typeSign'=>6],
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $perId,'typeName' => '备注','isHidden'=>1,'type'=>0,'isRequired'=>0,'typeSign'=>7],
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $perId,'typeName' => '同行人数','isHidden'=>1,'type'=>0,'isRequired'=>0,'typeSign'=>5]
            ]);
//            商务
            DB::table('visitorTypeSet')->insert([
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $busId,'typeName' => '拍照','isHidden'=>1,'type'=>0,'isRequired'=>0,'typeSign'=>1],
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $busId,'typeName' => '性别','isHidden'=>0,'type'=>1,'isRequired'=>0,'typeSign'=>2],
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $busId,'typeName' => '邮箱','isHidden'=>1,'type'=>0,'isRequired'=>0,'typeSign'=>4],
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $busId,'typeName' => '公司','isHidden'=>1,'type'=>0,'isRequired'=>0,'typeSign'=>8],
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $busId,'typeName' => '备注','isHidden'=>1,'type'=>0,'isRequired'=>0,'typeSign'=>7],
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $busId,'typeName' => '同行人数','isHidden'=>1,'type'=>0,'isRequired'=>0,'typeSign'=>5]
            ]);
//            其他
            DB::table('visitorTypeSet')->insert([
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $othId,'typeName' => '拍照','isHidden'=>1,'type'=>0,'isRequired'=>0,'typeSign'=>1],
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $othId,'typeName' => '性别','isHidden'=>0,'type'=>1,'isRequired'=>0,'typeSign'=>2],
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $othId,'typeName' => '邮箱','isHidden'=>1,'type'=>0,'isRequired'=>0,'typeSign'=>4],
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $othId,'typeName' => '身份证','isHidden'=>0,'type'=>0,'isRequired'=>0,'typeSign'=>6],
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $othId,'typeName' => '备注','isHidden'=>1,'type'=>0,'isRequired'=>0,'typeSign'=>7],
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $othId,'typeName' => '同行人数','isHidden'=>1,'type'=>0,'isRequired'=>0,'typeSign'=>5]
            ]);
            //面试便签
            DB::table('visitorInfo')->insert([
                ['cmpId' => $cmpId, 'visitorTypeId' => $visId,'typeName' => '性别','isHidden'=>0,'type'=>1],
                ['cmpId' => $cmpId, 'visitorTypeId' => $visId,'typeName' => '邮箱','isHidden'=>1,'type'=>1],
                ['cmpId' => $cmpId, 'visitorTypeId' => $visId,'typeName' => '身份证','isHidden'=>0,'type'=>1],
                ['cmpId' => $cmpId, 'visitorTypeId' => $visId,'typeName' => '备注','isHidden'=>1,'type'=>1]
            ]);
            //商务便签
            DB::table('visitorInfo')->insert([
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $busId,'typeName' => '性别','isHidden'=>0,'type'=>2],
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $busId,'typeName' => '邮箱','isHidden'=>1,'type'=>2],
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $busId,'typeName' => '公司','isHidden'=>1,'type'=>2],
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $busId,'typeName' => '备注','isHidden'=>0,'type'=>2],
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $busId,'typeName' => '同行人数','isHidden'=>0,'type'=>2]
            ]);
            //亲友便签
            DB::table('visitorInfo')->insert([
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $perId,'typeName' => '性别','isHidden'=>0,'type'=>3],
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $perId,'typeName' => '邮箱','isHidden'=>1,'type'=>3],
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $perId,'typeName' => '身份证','isHidden'=>0,'type'=>3],
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $perId,'typeName' => '备注','isHidden'=>0,'type'=>3],
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $perId,'typeName' => '同行人数','isHidden'=>1,'type'=>3]
            ]);
            //其他便签
            DB::table('visitorInfo')->insert([
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $othId,'typeName' => '性别','isHidden'=>0,'type'=>4],
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $othId,'typeName' => '邮箱','isHidden'=>1,'type'=>4],
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $othId,'typeName' => '身份证','isHidden'=>0,'type'=>4],
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $othId,'typeName' => '备注','isHidden'=>0,'type'=>4],
                ['cmpId' => $cmpId, 'visitorTypeId' =>  $othId,'typeName' => '同行人数','isHidden'=>1,'type'=>4]
            ]);
        } catch (\Exception $e) {
            return response()->json(['code'=>400,'msg'=>'配置错误','data'=>['token'=>'']]);
        }
        if($type=="1"){
            return response()->json(['code'=>200,'msg'=>'注册成功','data'=>['token'=>$ipadToken,'cmpId'=>$cmpId]]);
        }elseif($type=="2"){
            return response()->json(['code'=>200,'msg'=>'注册成功','data'=>['token'=>$token,'cmpId'=>$cmpId]]);
        }
    }
//    登录
    public function login(Request $request)
    {
        $data = $request->all();
        $mobile = $data['mobile'];
        $pwd = $data['pwd'];
        $type = $data['type'];
        if(empty($mobile) || empty($pwd) || empty($type)){
            return response()->json(['code'=>400,'msg'=>'信息错误','data'=>['token'=>'']]);
        }
        $userId = DB::table('userAdm')->where('mobile',$mobile)->select(['id','salt','passWord','createdAt'])->first();
        if(empty($userId)){
            return response()->json(['code'=>400,'msg'=>'用户不存在','data'=>'']);
        }
        $salt = $userId->salt;
        $pwd = md5($pwd.$salt);
        if($pwd != $userId->passWord){
            return response()->json(['code'=>400,'msg'=>'用户名或密码错误','data'=>'']);
        }
        $cmpInfo = DB::table('cmpInfo')->where('userId',$userId->id)->first();
        if(empty($cmpInfo)){
            return response()->json(['code'=>400,'msg'=>'公司不存在','data'=>'']);
        }else{
            $cmpId = $cmpInfo->id;
            $cmpStep = $cmpInfo->status;
            $cmpName = $cmpInfo->cmpName;
        }
        $temp=($cmpStep==3) ? 1 : 0;
        if($data['type']=="1"){
            $deviceInfo = DB::table('deviceInfo')->where('idfa',$data['idfa'])->first();
            if(empty($deviceInfo)){
                $name = '';
            }else{
                $name = $deviceInfo->deviceName;
            }
            $token = md5(str_random(30).time());
            $validity = time()+7*24*3600;
            $loginInfo = DB::table('multiDeviceLogin')->where([
                              ['idfa', '=', $data['idfa']],
                              ['uid', '=', $userId->id],
                             ])->get()->toArray();
            if(empty($loginInfo)){
                $result = DB::table('multiDeviceLogin')->insertGetId(
                    ['uid'=>$userId->id,'mobile' => $mobile,'type'=>'1','idfa'=>$data['idfa'],'token' => $token,'createdAt'=>time(),'validity'=>$validity]
                );
            }else{
                $result = DB::table('multiDeviceLogin')
                            ->where([['idfa', '=', $data['idfa']],['uid', '=', $userId->id],
                            ])->update(['token'=>$token,'validity'=>$validity]);
                 }
            
        }
        $orderInfo = DB::table('order')
            ->where([['userId','=',$userId->id],['status','=','2']])
            ->orderBy('id','desc')
            ->select('name','type','validity')
            ->first();
        if(empty($orderInfo)){
            $orderDay = floor((time() - $userId->createdAt)/24/3600);
            $orderValidity = date('Y-m-d',($userId->createdAt + 15*24*3600));
            $orderDay = 15-$orderDay ;
            if($orderDay <=0){
                $orderStatus = 0;
                $orderDay = 0;
            }else{
                $orderStatus = 1;
            }
            $order = ['orderType'=>0,'orderStatus'=>$orderStatus,'orderDay'=>$orderDay,'orderValidity'=>$orderValidity];
        }else{
            $order['orderType'] = 1;
            $expirationTime = $orderInfo->validity - time();
            if($expirationTime <= 0){
                $expirationTime = 0;
                $order['orderStatus'] = 0;
            }else{
                $order['orderStatus'] = 1;
            }
            $order['orderDay'] = floor(abs($expirationTime)/24/3600);
            $order['orderValidity'] = date('Y-m-d',$orderInfo->validity);
        }
        if($data['type']==2){
//            $order = ['orderType'=>0,'orderStatus'=>'','orderDay'=>'','orderValidity'=>''];
            $name = '';
            $token = md5(str_random(30).time());
            $validity = time()+7*24*3600;
            $result = User::where('mobile',$mobile)->update(['apiToken'=>$token,'validity'=>$validity]);
        }
        if($result){
            return response()->json(['code'=>200,'msg'=>'登录成功','data'=>['token'=>$token,'cmpId'=>$cmpId,'deviceName'=>$name,'cmpName'=>$cmpName,'step'=>$temp,'info'=>$data['mobile'],'order'=>$order]]);
        }else{
            return   response()->json(['code'=>400,'msg'=>'登录失败','data'=>['token'=>'']]);
        }
    }
    
    //忘记密码-修改密码
    public function resetPW(Request $request){
        $data = $request->all();
        $mobile = $data['mobile'];
        $newPwd = $data['pwd'];
        $salt = str_random(6);
        $newPwd = md5($newPwd.$salt);
        $type = $data['type'];
        if(empty($mobile) || empty($newPwd) || empty($type)) {
            return response()->json(['code'=>400,'msg'=>'数据缺失','data'=>'']);
        }
        $use=User::where('mobile',$mobile)->first();
        if(empty($use)){
            return response()->json(['code'=>400,'msg'=>'手机号不存在']);
        }
        $postMessage = $data['info'];
        $redisMessage  = Redis::get($mobile.'info');
        $redisTime = Redis::get($mobile.'infoTime');
        $nowTime = time();
        $timeApart = $nowTime -  $redisTime;
        if($timeApart<0 || $timeApart>300){
            return response()->json(['code'=>400,'msg'=>'验证码已过期','data'=>['token'=>'']]);
        }
        if( $postMessage != $redisMessage)
        {
            return response()->json(['code'=>400,'msg'=>'验证码错误','data'=>['token'=>'']]);
        }
        $cmpInfo = DB::table('cmpInfo')->where('userId',$use->id)->first();
        if(empty($cmpInfo)){
            return response(['code'=>400,'msg'=>'公司不存在','data'=>'']);
        }else{
            $cmpId = $cmpInfo->id;
            $cmpStep = $cmpInfo->status;
        }
        $step=($cmpStep==3) ? 1 : 0;
        if($type=="1"){
            $deviceInfo = DB::table('deviceInfo')->where('idfa',$data['idfa'])->first();
            if(empty($deviceInfo)){
                $name = '';
            }else{
                $name = $deviceInfo->deviceName;
            }
        }else{
            $name = '';
        }
        if($type==2){
            $token = md5(str_random(30).time());
            $validity = time()+7*24*3600;
            $result = User::where('mobile',$mobile)->update(['apiToken'=>$token,'passWord'=>$newPwd,'validity'=>$validity,'salt'=>$salt]);
        }
        if($type==1){
            $token = md5(str_random(30).time());
            $validity = time()+7*24*3600;
            $result = User::where('mobile',$mobile)->update(['ipadToken'=>$token,'passWord'=>$newPwd,'ipadValidity'=>$validity,'salt'=>$salt]);
            DB::table('multiDeviceLogin')->where('uid', '=', $use->id)->delete();
            DB::table('multiDeviceLogin')->insertGetId(
                ['uid'=>$use->id,'mobile' => $mobile,'type'=>'1','idfa'=>$data['idfa'],'token' => $token,'createdAt'=>time(),'validity'=>$validity]
            );
        }
        if($result){
            return response()->json(['code'=>200,'msg'=>'密码修改成功','data'=>['token'=>$token,'cmpId'=>$cmpId,'deviceName'=>$name,'step'=>$step]]);
        }else{
            return response()->json(['code'=>400,'msg'=>'密码修改失败','data'=>'']);
        }
    }
    public function version($id){
        $newVersion = str_replace('.','',$id);
        $versionInfo = DB::table('appVersion')->where('id','=',1)->first();
        $version = str_replace('.','',$versionInfo->version);
        $info = $newVersion < $version ? '1' : '0';
        if($info == 1){
            return response()->json(['code'=>200,'msg'=>'请求成功','data'=>['href'=>$versionInfo->href,'version'=>1]]);
        }else{
            return response()->json(['code'=>200,'msg'=>'请求成功','data'=>['href'=>$versionInfo->href,'version'=>0]]);
        }
    }
}
